package seatiger.tomcat.catalina.connector;

import seatiger.tomcat.catalina.Constants;
import seatiger.tomcat.catalina.Response;
import seatiger.tomcat.util.StringManager;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 对socket.getOutputSteam()的装饰
 */
@Deprecated
public class ResponseStream extends ServletOutputStream {
    /**
     *  和客户端连接的 OutputStream
     */
    private OutputStream output;

    private Response response;

    /**
     * 当flush 数据的时候 是否需要提交数据
     */
    private boolean commit = false;

    /**
     * 这个stream是否已经关闭了
     */
    private boolean closed = false;

    protected static StringManager sm = StringManager.getManager(Constants.PACKAGE_CONNECTOR);

    public ResponseStream(Response response){
        this.output = response.getStream();
        this.response = response;
        this.commit = false;
        this.closed = false;
    }
    @Override
    public void write(int b) throws IOException {
        if (closed) {
            throw new IOException(sm.getString("responseStream.write.closed"));
        }
        ((ResponseBase) response).write(b);
    }

    @Override
    public void write(byte[] b) throws IOException {
        write(b,0,b.length);
    }

    @Override
    public void write(byte b[], int off, int len) throws IOException {
        if (closed) {
            throw new IOException(sm.getString("responseStream.write.closed"));
        }
        ((ResponseBase) response).write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        if(closed){
            throw new IOException("responseStream.flush.closed");
        }
        if(commit){
            ((ResponseBase)response).flushBuffer();
        }
    }

    @Override
    public void close() throws IOException {
        if(closed){
            throw new IOException("responseStream.flush.closed");
        }
        ((ResponseBase)response).flushBuffer();
        closed = true;
    }

    public boolean isCommit() {
        return commit;
    }

    public void setCommit(boolean commit) {
        this.commit = commit;
    }

    public boolean isClosed() {
        return closed;
    }
}
